package com.zjjh.gateway.filter;

import com.ares.basic.exception.BusinessException;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class JwtAuthurationFilter implements GatewayFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String currentUrl = exchange.getRequest().getURI().getPath();
        //1:不需要认证的url
        int permit = shouldSkip(currentUrl);
        if(permit == 3) {
            return chain.filter(exchange);
        }
        //第一步:解析出我们Authorization的请求头  value为: “bearer XXXXXXXXXXXXXX”
        String authHeader = exchange.getRequest().getHeaders().getFirst("Authorization");

        if(permit == 2 && org.apache.commons.lang3.StringUtils.isEmpty(authHeader)) {
            return chain.filter(exchange);
        }

        if(permit == 1 && org.apache.commons.lang3.StringUtils.isEmpty(authHeader)) {
            throw new BusinessException("赶紧登陆吧");
        }
        if(!StringUtils.isEmpty(authHeader)) {
            // todo jwt token 认证
//            JWTPayload payload = JWTUtils.unsign(authHeader, JWTPayload.class);
//            if (payload == null) {
//                throw new BusinessException("赶紧登陆吧");
//            }
        }
        ServerHttpRequest newRequest = exchange.getRequest().mutate()
                .header("userId", "123131232131231312")
                .build();
        return chain.filter(exchange.mutate().request(newRequest).build());
    }

    /**
     * 方法实现说明:
     *  路径中包含api的需要登陆认证
     *  路径中包含free的可登陆可不登录
     *  路径中包含anon的无需登陆，直接放行
     *
     * @author:smlz
     * @param currentUrl 当前请求路径
     * @return:
     * @exception:
     * @date:2019/12/26 13:49
     */
    private int shouldSkip(String currentUrl) {
        //比如/oauth/** 可以匹配/oauth/token    /oauth/check_token等
//        PathMatcher pathMatcher = new AntPathMatcher();
//        if(pathMatcher.match("/**/api/**",currentUrl)) {
//            return 1;
//        }else if (pathMatcher.match("/**/free/**",currentUrl)){
//            return 2;
//        }else if (pathMatcher.match("/**/anon/**",currentUrl)){
//            return 3;
//        }
        return 3;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
